package com.emit.utils;

import com.emit.vo.MenuVO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.List;
import java.util.Map;

/**
 * @author zhangchao
 * @version 1.0.0
 * @date 2021-10-28
 */
public class MenuTreeUtil {
    /**
     * 根节点对象存放到这里
     */
    private final List<MenuVO> rootList;

    /**
     * 其他节点存放到这里，可以包含根节点
     */
    private final List<MenuVO> bodyList;

    public MenuTreeUtil(List<MenuVO> rootList, List<MenuVO> bodyList) {
        this.rootList = rootList;
        this.bodyList = bodyList;
    }

    public List<MenuVO> getTree(){   //调用的方法入口
        if(bodyList != null && !bodyList.isEmpty()){
            //声明一个map，用来过滤已操作过的数据
            Map<Long,Long> map = Maps.newHashMapWithExpectedSize(bodyList.size());
            rootList.forEach(beanTree -> getChild(beanTree,map));
            return rootList;
        }
        return null;
    }


    private void getChild(MenuVO beanTree, Map<Long, Long> map){
        List<MenuVO> childList = Lists.newArrayList();
        bodyList.stream()
                .filter(c -> !map.containsKey(c.getId()))
                .filter(c ->c.getParentId().equals(beanTree.getId()))
                .forEach(c ->{
                    map.put(c.getId(),c.getParentId());
                    getChild(c,map);
                    childList.add(c);
                });
        beanTree.setChildren(childList);
    }
}
